package controllers

import (
	json2 "encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"strconv"
	"time"
	"user-manger-system/cache"
	"user-manger-system/models"
	"user-manger-system/pkg"
)

type UserControllers struct {
	beego.Controller
}

func (c *UserControllers) Login() {
	username := c.GetString("username")
	password := c.GetString("password")
	if username == "" || password == "" {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "用户名或者密码为空",
		}
		c.ServeJSON()
		return
	}

	login := "login_error" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, login).Int()
	if errCount >= 3 {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "密码错误3次禁止登录",
		}
		c.ServeJSON()
		return
	}

	var err error
	var user models.User
	err = models.DB.Table("users").Where("username=?", username).First(&user).Debug().Error
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "用户查询失败",
		}
		c.ServeJSON()
		return
	}
	if user.ID == 0 {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "用户不存在",
		}
		c.ServeJSON()
		return
	}

	if user.Password != pkg.Md5Str(password) {
		cache.Rdb.Incr(cache.Ctx, login)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, login, 3, time.Hour*2)
			c.Data["json"] = map[string]interface{}{
				"code": 500,
				"msg":  "密码错误次数3次，封禁10分钟",
			}
			c.ServeJSON()
			return
		}

		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "密码错误",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "登录成功",
	}
	c.ServeJSON()
	return
}

func (c *UserControllers) List() {
	data := "data_list"
	cacheJson, _ := cache.Rdb.Get(cache.Ctx, data).Result()
	var user []models.User
	if cacheJson == "" {
		models.DB.Model(&models.User{}).Find(&user)
		json, _ := json2.Marshal(user)
		cache.Rdb.Set(cache.Ctx, data, json, time.Hour*2)
	} else {
		err := json2.Unmarshal([]byte(cacheJson), &user)
		if err != nil {
			c.Data["json"] = map[string]interface{}{
				"code": 0,
				"msg":  "缓存数据读取失败",
			}
			c.ServeJSON()
			return
		}
	}
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"data": user,
		"msg":  "success",
	}
	c.ServeJSON()
	return
}

func (c *UserControllers) Detail() {
	id, _ := c.GetInt("id")
	data := "data_id_" + strconv.Itoa(id)
	cacheJson, _ := cache.Rdb.Get(cache.Ctx, data).Result()
	var user models.User
	if cacheJson == "" {
		models.DB.Model(&models.User{}).Where("id=?", id).First(&user)
		json, _ := json2.Marshal(user)
		cache.Rdb.Set(cache.Ctx, data, json, time.Hour*2)
	} else {
		err := json2.Unmarshal([]byte(cacheJson), &user)
		if err != nil {
			c.Data["json"] = map[string]interface{}{
				"code": 0,
				"msg":  "缓存数据读取失败",
			}
			c.ServeJSON()
			return
		}
	}
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"data": user,
		"msg":  "success",
	}
	c.ServeJSON()
	return
}
